package com.gzsxy.esjy.pool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadFactory 给线程命名，查看创建线程数,给线程设置是否是后台运行,设置线程优先级
 * @author zhangxiaolong
 * @date 2022/7/6 9:36
 */
public class DefaultThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup threadGroup;
    private final AtomicInteger currentThreadNumber = new AtomicInteger(1);
    private final String namePrefix;
    private int priority = Thread.NORM_PRIORITY;
    private boolean isDaemon = false;
    
    private final static DefaultThreadFactory defaultThreadFactory = new DefaultThreadFactory("nio", false, Thread.NORM_PRIORITY) ;

    public static DefaultThreadFactory defaultThreadFactory() {
    	return defaultThreadFactory ;
    }
    
    
    public DefaultThreadFactory(String prefix) {
        this(prefix, false);
    }

    public DefaultThreadFactory(String prefix, boolean isDaemon) {
        this(prefix, isDaemon, Thread.NORM_PRIORITY);
    }

    public DefaultThreadFactory(String prefix, boolean isDaemon, int priority) {
        SecurityManager s = System.getSecurityManager();
        this.threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        //getAndIncrement以原子方式将当前值加 1。方法是返回旧值（即加1前的原始值）
        this.namePrefix = prefix + "-" + poolNumber.getAndIncrement() + "-thread-";
        this.isDaemon = isDaemon;
        this.priority = priority;
    }

    @Override
    public Thread newThread(Runnable r) {
        //给线程命名，名字有规律，形如 pool-N-thread-M (N:表示第几个线程池；M表示线程池内的第几个线程）
        Thread thread = new Thread(threadGroup, r, namePrefix + currentThreadNumber.getAndIncrement(), 0);
        //指定是否守护线程，守护线程不阻塞进程
        thread.setDaemon(isDaemon);
        //设置线程优先级
        thread.setPriority(priority);
        return thread;
    }
}
